package com.koushikdutta.ion.loader;

import com.example.ohosasynclibrary.async.DataEmitter;
import com.example.ohosasynclibrary.async.FileDataEmitter;
import com.example.ohosasynclibrary.async.future.Future;
import com.example.ohosasynclibrary.async.future.FutureCallback;
import com.example.ohosasynclibrary.async.future.SimpleFuture;
import com.example.ohosasynclibrary.async.http.AsyncHttpRequest;
import com.example.ohosasynclibrary.async.util.StreamUtility;
import com.example.ohosasynclibrary.async.util.TextUtils;
import com.koushikdutta.ion.Ion;
import com.koushikdutta.ion.IonLog;
import com.koushikdutta.ion.ResponseServedFrom;
import com.koushikdutta.ion.bitmap.BitmapInfo;
import com.koushikdutta.ion.bitmap.IonBitmapCache;
import ohos.agp.utils.Point;
import ohos.app.Context;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.utils.net.Uri;

import java.io.File;
import java.io.FileInputStream;

/**
 * Created by koush on 5/22/13.
 */
public class FileLoader extends StreamLoader {
    private static final class FileFuture extends SimpleFuture<DataEmitter> {
    }

    @Override
    public Future<BitmapInfo> loadBitmap(final Context context, final Ion ion, final String key, final String uri, final int resizeWidth, final int resizeHeight,
                                         final boolean animateGif) {
        if (uri == null || !uri.startsWith("file:/"))
            return null;

        final SimpleFuture<BitmapInfo> ret = new SimpleFuture<BitmapInfo>();

        IonLog.d("FileLoader", "Loading file bitmap " + uri + " " + resizeWidth + "," + resizeHeight);

        Ion.getBitmapLoadExecutorService().execute(new Runnable() {
            @Override
            public void run() {
                if (ret.isCancelled()) {
                    IonLog.d("FileLoader", "Bitmap load cancelled (no longer needed)");
                    return;
                }
                try {
                    File file = new File(Uri.parse(uri).getDecodedPath());
                    String path = file.getCanonicalPath();
                    String mimeType = "image/*";
                    if (!TextUtils.isEmpty(path) && path.contains(".")) {
                        mimeType = "image/".concat(path.substring(path.lastIndexOf(".") + 1).toLowerCase());
                    }
                    IonLog.i("mimeType8989----" + mimeType);
                    ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
                    sourceOptions.formatHint = mimeType;
                    ImageSource imageSource = ImageSource.create(file, sourceOptions);
                    ImageSource.DecodingOptions options = ion.getBitmapCache().prepareBitmapOptions(imageSource.getImageInfo().size, resizeWidth, resizeHeight);
                    Point size = new Point(options.desiredSize.width, options.desiredSize.height);
                    BitmapInfo info;
                    if (animateGif && TextUtils.equals("image/gif", mimeType)) {
                        FileInputStream fin = new FileInputStream(file);
                        try {
                            info = loadGif(key, size, fin, mimeType);
                        } finally {
                            StreamUtility.closeQuietly(fin);
                        }
                    } else {
                        PixelMap bitmap = IonBitmapCache.loadBitmap(file, options);
                        if (bitmap == null)
                            throw new Exception("Bitmap failed to load");
                        info = new BitmapInfo(key, mimeType, bitmap, size);
                    }
                    info.servedFrom = ResponseServedFrom.LOADED_FROM_CACHE;
                    ret.setComplete(info);
                } catch (OutOfMemoryError e) {
                    ret.setComplete(new Exception(e), null);
                } catch (Exception e) {
                    ret.setComplete(e);
                }
            }
        });

        return ret;
    }

    @Override
    public Future<DataEmitter> load(final Ion ion, final AsyncHttpRequest request, final FutureCallback<LoaderEmitter> callback) {
        if (request.getUri().getScheme() == null || !request.getUri().getScheme().startsWith("file"))
            return null;
        final FileFuture ret = new FileFuture();
        ion.getHttpClient().getServer().post(new Runnable() {
            @Override
            public void run() {
                File file = new File(Uri.parse(request.getUri().toString()).getDecodedPath());
                FileDataEmitter emitter = new FileDataEmitter(ion.getHttpClient().getServer(), file);
                ret.setComplete(emitter);
                callback.onCompleted(null, new LoaderEmitter(emitter, (int) file.length(), ResponseServedFrom.LOADED_FROM_CACHE, null, request));
            }
        });
        return ret;
    }
}
